package com.caiyi.financial.nirvana.sms.handler;

import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.IRedisQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by Mario on 2017/12/20 0020.
 * 项目启动
 */
@Component
public class RedisQueueHandler extends ApplicationHandler {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(RedisQueueHandler.class);

    /**
     * start flag
     */
    private boolean start = true;

    @Override
    public void start(ApplicationContext applicationContext) {
        Map<String, IRedisQueue> allRedisQueue = applicationContext.getBeansOfType(IRedisQueue.class);
        for (IRedisQueue queue : allRedisQueue.values()) {
            new Thread(() -> {
                while (start) {
                    try {
                        List<String> list = JedisService.brpop(5, queue.key());
                        queue.run(list);
                    } catch (Exception e) {
                        try {
                            Thread.sleep(1000);
                        } catch (Exception e1) {
                        }
                        logger.error(queue.getClass().getName() + " - 异常:", e);
                    }
                }
            }, queue.getClass().getName()).start();
            logger.info("已为 : {} - {} 启动线程", queue.getClass().getName(), queue.key());
        }
    }

}
